#!/usr/bin/python

'''
Created On: April, 29 2025
'''

import os
import sys


def get_title_from_file(file_path):
    title = None
    try:
        with open(file_path, "r") as f:
            for line in f.readlines():
                if "title:" in line:
                    title = line[len("title:"):]
                    title = title.strip()
                    break
    except (FileNotFoundError, PermissionError):
        pass
    return title


def get_file_lines(file_path):
    lines = None
    try:
        with open(file_path, "r") as f:
            lines = f.readlines()
    except (FileNotFoundError, PermissionError):
        pass

    return lines


def check_exist(filepath, lines):
    for line in lines:
        if filepath in line:
            return True
    return False


def check_duplicated(in_title, in_path, output):
    for (title, path) in output:
        if title == in_title or path == in_path:
            print(f"Duplicated [{title}]({path})")
            return True
    return False


def process_dir(root_dir, relative_dir, output):
    full_path = os.path.join(root_dir, relative_dir)
    ignored_entries = ["scaffolds", "themes", "dropped", "about", "README.md", "index.md"]
    for entry in sorted(os.listdir(full_path)):
        if entry in ignored_entries:
            continue
        # if entry == "multimedia":
        #     continue
        entry_full_path = os.path.join(full_path, entry)
        if os.path.isdir(entry_full_path):
            process_dir(root_dir, os.path.join(relative_dir, entry), output)
        elif os.path.isfile(entry_full_path) and entry_full_path.endswith(".md"):
            title = get_title_from_file(entry_full_path)
            if title and title != "":
                check_duplicated(title, os.path.join(relative_dir, entry), output)
                output.append((title, os.path.join(relative_dir, entry)))
            else:
                print("Cannot get title: ", entry_full_path)


def main():
    root_dir = sys.argv[1]
    output = []

    readme_file = "README.md"

    contents = get_file_lines(os.path.join(root_dir, readme_file))

    process_dir(root_dir, ".", output)

    # for (title, path) in output:
    #     print(f"[{title}]({path})")
    #     print()

    for (title, path) in output:
        if not check_exist(path, contents):
            print(f"[{title}]({path})")
            # print(f"Missing file {path}")

if __name__ == "__main__":
    main()
